﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OneBarCode.Utils;
using System.Threading;
using System.IO.Ports;
using System.IO;
using easywork.Utils;
using System.Management;

namespace OneBarCode
{
    public partial class FrmZebra : Form
    {
        int highTemp = 0;
        int lowTemp = 0;
        bool iflistening = false;
        public FrmZebra()
        {
            InitializeComponent();
        }
        #region 获取端口名称
        /// <summary>
        /// 枚举win32 api
        /// </summary>
        public enum HardwareEnum
        {
            // 硬件
            Win32_Processor, // CPU 处理器
            Win32_PhysicalMemory, // 物理内存条
            Win32_Keyboard, // 键盘
            Win32_PointingDevice, // 点输入设备，包括鼠标。
            Win32_FloppyDrive, // 软盘驱动器
            Win32_DiskDrive, // 硬盘驱动器
            Win32_CDROMDrive, // 光盘驱动器
            Win32_BaseBoard, // 主板
            Win32_BIOS, // BIOS 芯片
            Win32_ParallelPort, // 并口
            Win32_SerialPort, // 串口
            Win32_SerialPortConfiguration, // 串口配置
            Win32_SoundDevice, // 多媒体设置，一般指声卡。
            Win32_SystemSlot, // 主板插槽 (ISA & PCI & AGP)
            Win32_USBController, // USB 控制器
            Win32_NetworkAdapter, // 网络适配器
            Win32_NetworkAdapterConfiguration, // 网络适配器设置
            Win32_Printer, // 打印机
            Win32_PrinterConfiguration, // 打印机设置
            Win32_PrintJob, // 打印机任务
            Win32_TCPIPPrinterPort, // 打印机端口
            Win32_POTSModem, // MODEM
            Win32_POTSModemToSerialPort, // MODEM 端口
            Win32_DesktopMonitor, // 显示器
            Win32_DisplayConfiguration, // 显卡
            Win32_DisplayControllerConfiguration, // 显卡设置
            Win32_VideoController, // 显卡细节。
            Win32_VideoSettings, // 显卡支持的显示模式。

            // 操作系统
            Win32_TimeZone, // 时区
            Win32_SystemDriver, // 驱动程序
            Win32_DiskPartition, // 磁盘分区
            Win32_LogicalDisk, // 逻辑磁盘
            Win32_LogicalDiskToPartition, // 逻辑磁盘所在分区及始末位置。
            Win32_LogicalMemoryConfiguration, // 逻辑内存配置
            Win32_PageFile, // 系统页文件信息
            Win32_PageFileSetting, // 页文件设置
            Win32_BootConfiguration, // 系统启动配置
            Win32_ComputerSystem, // 计算机信息简要
            Win32_OperatingSystem, // 操作系统信息
            Win32_StartupCommand, // 系统自动启动程序
            Win32_Service, // 系统安装的服务
            Win32_Group, // 系统管理组
            Win32_GroupUser, // 系统组帐号
            Win32_UserAccount, // 用户帐号
            Win32_Process, // 系统进程
            Win32_Thread, // 系统线程
            Win32_Share, // 共享
            Win32_NetworkClient, // 已安装的网络客户端
            Win32_NetworkProtocol, // 已安装的网络协议
            Win32_PnPEntity,//all device
        }
        /// <summary>
        /// WMI取硬件信息
        /// </summary>
        /// <param name="hardType"></param>
        /// <param name="propKey"></param>
        /// <returns></returns>
        public static string[] MulGetHardwareInfo(HardwareEnum hardType, string propKey)
        {

            List<string> strs = new List<string>();
            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType))
                {
                    var hardInfos = searcher.Get();
                    foreach (var hardInfo in hardInfos)
                    {
                        if (hardInfo.Properties[propKey].Value != null)
                            if (hardInfo.Properties[propKey].Value.ToString().Contains("COM"))
                            {
                                strs.Add(hardInfo.Properties[propKey].Value.ToString());
                            }

                    }
                    searcher.Dispose();
                }
                return strs.ToArray();
            }
            catch
            {
                return null;
            }
            finally
            { strs = null; }
        }
        #endregion
        private void btnOk_Click(object sender, EventArgs e)
        {
            //strSqlTemp = string.Format("insert into SN2Num(SerialNum,SN) values ('{0}','{1}')", 1231457, 123);
            //DataBaseManager.executeNonQuery(strSqlTemp); return;
            //try
            //{
            //    BarcodePrint zb = new BarcodePrint();
            //    string mycommanglines = System.IO.File.ReadAllText(@"d:\aaa.txt");//print.txt里写了条码机的命令  
            //    //mycommanglines = "";
            //    //mycommanglines += "^XA";
            //    //mycommanglines += "^LH30,30";
            //    //mycommanglines += "^FO20,10^ADFDZEBRA^FS";
            //    //mycommanglines += "^FO20,60^B3^FDAAA001^FS";
            //    //mycommanglines += "^XZ";//^XA^LH30,30^FO20,10^ADFDZEBRA^FS^FO20,60^B3^FDAAA001^FS^XZ
            //    mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSB^LT0^MNM^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0180\r\n^LS0\r\n^BY2,2,48^FT15,75^B3N,N,,Y,N\r\n^FD" + "LKJIGHABCDEF" + "^FS\r\n^FT30,131^A0N,28,28^FH\\^FDDATE:" + DateTime.Now.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
            //    mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,46^B3N,N,,Y,N\r\n^FD" + "123456789876" + "^FS\r\n^FT330,81^A0N,17,19^FH\\^FD" + SystemConfig.SerialNum + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
            //    zb.Open("COM14:");
            //    zb.Write(mycommanglines);
            //    zb.Close();
            //}
            //catch (Exception)
            //{

            //    throw;
            //}
            string strmac = "test12345678";
            string comSendName = "";
            if (combPortPrinter.SelectedIndex >= 0)
            {
                comSendName = combPortPrinter.Text;
            }
            BarcodePrint zb = new BarcodePrint();
            string mycommanglines = "";// System.IO.File.ReadAllText(@"d:\aaa.txt");//print.txt里写了条码机的命令  F:\公司项目\C#项目\批量生成条形码并导出为图片\20160328.prn
            mycommanglines = "";
            //mycommanglines += "^XA";
            //mycommanglines += "^LH30,30";
            //mycommanglines += "^FO20,10^ADFDZEBRA^FS";
            //mycommanglines += "^FO20,60^B3^FDAAA001^FS";
            //mycommanglines += "^XZ";//^XA^LH30,30^FO20,10^ADFDZEBRA^FS^FO20,60^B3^FDAAA001^FS^XZ
            //mycommanglines = "I8,A,001\r\n\r\n\r\nQ224,024\r\nq863\r\nrN\r\nS4\r\nD7\r\nZT\r\nJF\r\nO\r\nR279,0\r\nf100\r\nN\r\nB3,29,0,3,2,4,88,B,\"" + strmac + "\"\r\n\r\nP1\r\n";

            //mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSB^LT0^MNM^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0180\r\n^LS0\r\n^BY2,2,48^FT15,75^B3N,N,,Y,N\r\n^FD" + strmac + "^FS\r\n^FT30,131^A0N,28,28^FH\\^FDDATE:" + DateTime.Now.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
            //20160328修改，条形码高度变为原来的一半
            //mycommanglines = "I8,A,001\r\n\r\n\r\nQ100,024\r\nq863\r\nrN\r\nS4\r\nD7\r\nZT\r\nJF\r\nO\r\nR217,0\r\nf100\r\nN\r\nB31,18,0,3,2,4,24,B,\"" + strmac + "\"\r\nA101,62,0,4,1,1,N,\"DATE:" + DateTime.Now.ToShortDateString() + "\"\r\nP1\r\n";
            mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + strmac + "^FS\r\n^FT97,81^A0N,22,38^FH\\^FDDATE:" + DateTime.Now.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
            //添加汉字显示：“生产日期”
            mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n~DG000.GRF,01024,016,\r\n,::::::::::::::::::::::::::::::::I060J0E0N0860,01C70J0F0H07FHF01C67F0,01C60H03FHF802006008E638,01C60H07FHFC0700707FF630,03860I02060020060086630,03FHFC0070F00700701C7730,03060I030C00200600FE7F8,07060I031C00700701C6630,0E060H03FHFE03FFE0086630,I070H07FHFC0700701FE7301C,H0IF8030J02006008E6381E,01FHFH070J0700701C67F01C,I060H020J0200607FE630,I070H070J070070H01F30,I060H060J0200600CCE381E,I060H060J07FHF01C5C301C,07FHFE0E0J0200603078300E,07FIF1C0J070070703CF0,M080J020K01860,,:::::::::::^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + strmac + "^FS\r\n^FT209,83^A0N,19,24^FH\\^FD" + DateTime.Now.ToShortDateString() + "^FS\r\n^FT96,96^XG000.GRF,1,1^FS\r\n^PQ1,0,1,Y^XZ\r\n^XA^ID000.GRF^FS^XZ\r\n";
            //添加序列号（编号）到右下角
            mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,46^B3N,N,,Y,N\r\n^FD" + strmac + "^FS\r\n^FT330,81^A0N,17,19^FH\\^FD" + SystemConfig.SerialNum + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
            comSendName = comSendName.Split('(')[1].Split(')')[0];
            //zb.Open(comSendName);
            //zb.Write(mycommanglines);
            //zb.Close();
            if (zb.Open(comSendName))
            {
                zb.Write(mycommanglines);
                //MessageBox.Show("123");
                zb.Close();
            }
            else
            { }
                SerialPort serialPortTemp = new SerialPort(comSendName, 9600, Parity.None, 8, StopBits.One);
                //serialPortTemp.Write(mycommanglines);
                serialPortTemp.Open();
                serialPortTemp.WriteLine(mycommanglines);
                serialPortTemp.Close();
            
        }



        SerialPort serialPort = null;//当前监听的串口
        int k = 0;//记录当前数据数量
        string currentData = "";//用于存放当前收到的数据
        private void btnReceive_Click(object sender, EventArgs e)
        {
            
            highTemp = 0;
            lowTemp = 0;
            #region
            //if (combHighTem.SelectedIndex < 0 || combLowTem.SelectedIndex < 0)
            //{
            //    MessageBox.Show("请设置允许温度范围", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}
            //highTemp = int.Parse(combHighTem.Text);
            //lowTemp = int.Parse(combLowTem.Text);
            //if (highTemp <= lowTemp)
            //{
            //    MessageBox.Show("最高温度应高于最低温度", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}
            if (radioButton1.Checked)
            {
                temperatureTemp = int.Parse(combLowTem.Text);
            }
            else
            {
                temperatureTemp = int.Parse(combHighTem.Text);
            }
            groupBox2.Enabled = false;
            groupBox3.Enabled = false;
            btnStopReceive.Enabled = true;
            btnFresh.Enabled = false;
            #endregion
            string comReceiveName = "";
            if (combPortReceive.SelectedIndex >= 0)
            {
                comReceiveName = combPortReceive.Text;
            }
            else
            {
                MessageBox.Show("请选择接收数据的端口", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            comReceiveName = comReceiveName.Split('(')[1].Split(')')[0];
            //serialPort = new SerialPort(comReceiveName, 9600, Parity.None, 8, StopBits.One);
            serialPort = new SerialPort(comReceiveName, 115200, Parity.None, 8, StopBits.One);

            //关键 为 serialPort1绑定事件句柄
            serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
            try
            {
                serialPort.Open();
                iflistening = true;
                lblStatus.Text = "正在监听数据...";
                MessageBox.Show("监听端口成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {

                MessageBox.Show("监听端口失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            btnReceive.Enabled = false;
        }

        //数据接收使用的代理
        private delegate void myDelegate(string s);

        //串口数据到达时的事件
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //关键 代理
            myDelegate md = new myDelegate(SetText);

            try
            {
                if (serialPort.IsOpen == true)
                {
                    byte[] readBuffer = new byte[serialPort.ReadBufferSize];
                    serialPort.Read(readBuffer, 0, readBuffer.Length);
                    string readstr = Encoding.UTF8.GetString(readBuffer);
                    readstr = readstr.Replace("\0", "");
                    currentData += readstr;
                    //return;
                    if (!currentData.StartsWith("0"))//0x
                    {
                        currentData = "";
                    }
                    else
                    {
                        if (currentData.Length >= 2 && !currentData.StartsWith("0x"))
                        {
                            currentData = "";
                        }
                    }
                    if (currentData.Length >= 34)
                    {
                        Invoke(md, currentData.Substring(2, 32));
                        currentData = "";
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }


        }
        /// <summary>
        /// 向打印机发送打印条码的命令
        /// </summary>
        /// <param name="strMAC"></param>
        private void sendDataToPrinter(string strMAC)
        {
            string strmac = strMAC.Substring(0, 12);
            string comSendName = "";
            if (combPortPrinter.SelectedIndex >= 0)
            {
                comSendName = combPortPrinter.Text;
            }
            //查询mac和SN对应关系表来确定是否打印过此mac
            strSqlTemp = string.Format("select * from SN2Num where SN='{0}'", strmac);
            dtTemp = DataBaseManager.ExecDataSet(strSqlTemp).Tables[0];
            BarcodePrint zb = new BarcodePrint();
            string mycommanglines = "";// System.IO.File.ReadAllText(@"d:\aaa.txt");//print.txt里写了条码机的命令  F:\公司项目\C#项目\批量生成条形码并导出为图片\20160328.prn
            mycommanglines = "";
            //mycommanglines += "^XA";
            //mycommanglines += "^LH30,30";
            //mycommanglines += "^FO20,10^ADFDZEBRA^FS";
            //mycommanglines += "^FO20,60^B3^FDAAA001^FS";
            //mycommanglines += "^XZ";//^XA^LH30,30^FO20,10^ADFDZEBRA^FS^FO20,60^B3^FDAAA001^FS^XZ
            //mycommanglines = "I8,A,001\r\n\r\n\r\nQ224,024\r\nq863\r\nrN\r\nS4\r\nD7\r\nZT\r\nJF\r\nO\r\nR279,0\r\nf100\r\nN\r\nB3,29,0,3,2,4,88,B,\"" + strmac + "\"\r\n\r\nP1\r\n";

            //mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSB^LT0^MNM^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0180\r\n^LS0\r\n^BY2,2,48^FT15,75^B3N,N,,Y,N\r\n^FD" + strmac + "^FS\r\n^FT30,131^A0N,28,28^FH\\^FDDATE:" + DateTime.Now.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
            //20160328修改，条形码高度变为原来的一半
            //mycommanglines = "I8,A,001\r\n\r\n\r\nQ100,024\r\nq863\r\nrN\r\nS4\r\nD7\r\nZT\r\nJF\r\nO\r\nR217,0\r\nf100\r\nN\r\nB31,18,0,3,2,4,24,B,\"" + strmac + "\"\r\nA101,62,0,4,1,1,N,\"DATE:" + DateTime.Now.ToShortDateString() + "\"\r\nP1\r\n";
           // mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + strmac + "^FS\r\n^FT97,81^A0N,22,38^FH\\^FDDATE:" + DateTime.Now.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
            //添加汉字显示：“生产日期”
           // mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n~DG000.GRF,01024,016,\r\n,::::::::::::::::::::::::::::::::I060J0E0N0860,01C70J0F0H07FHF01C67F0,01C60H03FHF802006008E638,01C60H07FHFC0700707FF630,03860I02060020060086630,03FHFC0070F00700701C7730,03060I030C00200600FE7F8,07060I031C00700701C6630,0E060H03FHFE03FFE0086630,I070H07FHFC0700701FE7301C,H0IF8030J02006008E6381E,01FHFH070J0700701C67F01C,I060H020J0200607FE630,I070H070J070070H01F30,I060H060J0200600CCE381E,I060H060J07FHF01C5C301C,07FHFE0E0J0200603078300E,07FIF1C0J070070703CF0,M080J020K01860,,:::::::::::^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + strmac + "^FS\r\n^FT209,83^A0N,19,24^FH\\^FD" + DateTime.Now.ToShortDateString() + "^FS\r\n^FT96,96^XG000.GRF,1,1^FS\r\n^PQ1,0,1,Y^XZ\r\n^XA^ID000.GRF^FS^XZ\r\n";
            //添加序列号（编号）到右下角
            mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,46^B3N,N,,Y,N\r\n^FD" + strmac + "^FS\r\n^FT330,81^A0N,17,19^FH\\^FD" + (dtTemp.Rows.Count>0?dtTemp.Rows[0]["SerialNum"].ToString():SystemConfig.SerialNum) + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
            comSendName = comSendName.Split('(')[1].Split(')')[0];
            //zb.Open(comSendName);
            //zb.Write(mycommanglines);
            //zb.Close();
            if (zb.Open(comSendName))
            {
                zb.Write(mycommanglines);
                zb.Close();
            }
            else
            {
                SerialPort serialPortTemp = new SerialPort(comSendName, 9600, Parity.None, 8, StopBits.One);
                //serialPortTemp.Write(mycommanglines);
                serialPortTemp.Open();
                serialPortTemp.WriteLine(mycommanglines);
                serialPortTemp.Close(); 
            }
            try
            {
                if (dtTemp.Rows.Count==0)//如果以前没有此mac相关信息
                {
                    strSqlTemp = string.Format("insert into SN2Num(SerialNum,SN) values ('{0}','{1}')", SystemConfig.SerialNum, strmac);
                    DataBaseManager.executeNonQuery(strSqlTemp);
                    if (int.Parse(SystemConfig.SerialNum)%120==0)
                    {
                        MessageBox.Show("已经检测120个，可以装盒了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    SystemConfig.SerialNum = string.Format("{0:D7}", int.Parse(SystemConfig.SerialNum) + 1);
                    strSqlTemp = string.Format("update SystemConfig set SerialNum='{0}'", SystemConfig.SerialNum);
                    DataBaseManager.executeNonQuery(strSqlTemp);
                }                
            }
            catch (Exception)
            {
                MessageBox.Show("保存数据失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        #region MyRegion

        string strSqlTemp = "";
        float temperature1 = 0;//测量温度
        float temperature2 = 0;//环境温度
        string strResult = "";//检测结果文字说明：即合格或者不合格
        bool ifResultOk = false;//检测结果
        string dbNameTemp = string.Empty;//用来区分是超声波前还是后，以便来判断往哪个数据库中插入数据
        int temperatureTemp = 0;//用来记录设置的温度
        DataTable dtTemp = null;//存储查询的上次检测数据
        string strMacTemp = string.Empty;
        bool ifCSBQ = true;
        bool ifExistMac ;
        bool ifOkLastTime;
        string fieldName4Time = string.Empty;
        string fieldName4Data = string.Empty;
        string fieldName4Result = string.Empty;
        string strMac4LastPrint = string.Empty;
        //分隔字符串并保存在指定目录下
        private void SetText(string str)
        {
            k++;
            strMacTemp = str.Substring(0, 12);
            try
            {
                temperature1 = float.Parse(str.Substring(18, 2) + "." + str.Substring(20, 2));
                temperature2 = float.Parse(str.Substring(28, 2) + "." + str.Substring(30, 2));
            }
            catch (Exception)
            {
                MessageBox.Show("数据错误！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            //if (temperature1 <= temperatureTemp + 1.8 && temperature1 >= temperatureTemp - 1.8 && temperature2 <= temperatureTemp + 0.8 && temperature2 >= temperatureTemp - 2.8)
            if (temperature1 <= temperatureTemp + 1.8 && temperature1 >= temperatureTemp - 1.8 && (combStatus.SelectedIndex == 0 ? (temperature2 <= temperature1 && temperature2 >= 33) : (temperature2 <= temperatureTemp + 0.8 && temperature2 >= temperatureTemp - 2.8)))
            {
                strResult = "合格!";
                ifResultOk = true;
            }
            else
            {
                strResult = "不合格!";
                ifResultOk = false;
            }
            if (k == 1)
            {
                richTextBox1.AppendText(k + ": " + str + "  " + combStatus.Text + "  " + strResult);
            }
            else
            {
                richTextBox1.AppendText("\r\n" + k + ": " + str + "  " + combStatus.Text + "  " + strResult);
            }
            richTextBox1.AppendText(" ");
            richTextBox1.ScrollToCaret();
            //将消息存到数据库中
            if (combStatus.Text=="超声波前")
            {
                ifCSBQ = true;
                dbNameTemp = "HistoryData";
                strSqlTemp = string.Format("select * from HistoryData where Mac='{0}'", strMacTemp);     
            }
            else
            {
                ifCSBQ = false;
                dbNameTemp = "HistoryData4After";
                strSqlTemp = string.Format("select * from HistoryData4After where Mac='{0}'", strMacTemp);
            }
            dtTemp = DataBaseManager.ExecDataSet(strSqlTemp).Tables[0];
            #region 判断是否已经存在该设备，并且如果已经存在则获取上次的检测结果
            if (dtTemp.Rows.Count>0)
            {
                ifExistMac = true;
                if (radioButton1.Checked)
                {
                    ifOkLastTime = (bool)dtTemp.Rows[0]["PassOrNot4High"];
                }
                else
                {
                    ifOkLastTime = (bool)dtTemp.Rows[0]["PassOrNot4Low"];
                }
            }
            else
            {
                ifExistMac = false;
                ifOkLastTime = false;
            }
            #endregion
            if (radioButton1.Checked)//低温段
            {
                fieldName4Time="ReceiveTime4Low";
                fieldName4Data="Data4Low";
                fieldName4Result="PassOrNot4Low";
            }
            else//高温段
            {
                fieldName4Time="ReceiveTime4High";
                fieldName4Data="Data4High";
                fieldName4Result="PassOrNot4High";
            }
            richTextBox1.AppendText(" （" + (ifOkLastTime ? "ok" : (dtTemp.Rows.Count > 0?"上次不合格":"只检测了一种"))+"）");
            if (ifExistMac)//如果已经存在该设备的数据
            {
                strSqlTemp = string.Format("update {0} set {1}='{2}',{3}='{4}',{5}='{6}' where Mac='{7}'", dbNameTemp, fieldName4Time, DateTime.Now.ToString("s"),
                    fieldName4Data, str, fieldName4Result, ifResultOk ? 1 : 0,strMacTemp);
            }
            else
            {
                strSqlTemp = string.Format("insert into {0}(Mac,{1},{2},{3}) values ('{4}','{5}','{6}','{7}')", dbNameTemp, fieldName4Time, fieldName4Data, fieldName4Result, 
                    strMacTemp,DateTime.Now.ToString("s"),str, ifResultOk ? 1 : 0);
            }
            try
            {
                //strSqlTemp = string.Format("insert into HistoryData(Mac,ReceiveTime,Data,PassOrNot) values ('{0}','{1}','{2}','{3}','{4}')", str.Substring(0, 12), DateTime.Now.ToString(), str, ifResultOk ? 1 : 0);
                DataBaseManager.executeNonQuery(strSqlTemp);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
            if (!ifCSBQ && ifResultOk&&ifOkLastTime)
            {
                if (strMac4LastPrint!=strMacTemp)
                {
                    sendDataToPrinter(str);
                    strMac4LastPrint = strMacTemp;
                }
                
            }
        }
        #endregion
        /// <summary>
        /// 停止监听端口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopReceive_Click(object sender, EventArgs e)
        {
            groupBox2.Enabled = true;
            groupBox3.Enabled = true;
            btnReceive.Enabled = true;
            btnFresh.Enabled = true;
            if (serialPort != null)
            {
                if (serialPort.IsOpen == true)
                    serialPort.Close();
                serialPort.Dispose();
                lblStatus.Text = "已经停止监听端口";
                iflistening = false;
                MessageBox.Show("停止监听端口成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            btnStopReceive.Enabled = false;
        }
        /// <summary>
        /// 初始化窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmZebra_Load(object sender, EventArgs e)
        {
            for (int i = 30; i <= 42; i++)
            {
                this.combHighTem.Items.Add(i);
                this.combLowTem.Items.Add(i);
            }
            combLowTem.SelectedIndex = 6;
            combHighTem.SelectedIndex = 10;
            //读取系统的端口初始化端口下拉列表
            //string[] portlist = SerialPort.GetPortNames();
            //portlist=MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
            //for (int i = 0; i < portlist.Length; i++)
            //{
            //    this.combPortReceive.Items.Add(portlist[i]);
            //    this.combPortPrinter.Items.Add(portlist[i]);
            //}
            string[] portlistOri = SerialPort.GetPortNames();
            string[] portlist = MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
            for (int i = 0; i < portlist.Length; i++)
            {
                for (int k = 0; k < portlistOri.Length; k++)
                {
                    if (portlist[i].Contains(portlistOri[k]))
                    {
                        this.combPortReceive.Items.Add(portlist[i]);
                        this.combPortPrinter.Items.Add(portlist[i]);
                        break;
                    }
                }

                //this.combPortReceive.Items.Add(portlist[i]);
                //this.combPortPrinter.Items.Add(portlist[i]);
            }
            if (combPortReceive.Items.Count > 0)
            {
                combPortReceive.SelectedIndex = 0;
            }
            if (combPortPrinter.Items.Count > 0)
            {
                combPortPrinter.SelectedIndex = 0;
            }
            this.combStatus.Items.Add("超声波前");
            this.combStatus.Items.Add("超声波后");
            this.combStatus.SelectedIndex = 0;
            #region 初始化序列号
            string strsql = string.Format("select * from SystemConfig");// 
            DataTable dt = DataBaseManager.ExecDataSet(strsql).Tables[0];
            SystemConfig.SerialNum = dt.Rows[0]["SerialNum"].ToString();
            #endregion
        }
        /// <summary>
        /// 清空数据显示区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClear_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            k = 0;
        }
        /// <summary>
        /// 查看历史数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnViewHistory_Click(object sender, EventArgs e)
        {
            FrmHistory frm = new FrmHistory();
            frm.Show();
        }

        private void btnFresh_Click(object sender, EventArgs e)
        {
            this.combPortReceive.Items.Clear();
            this.combPortPrinter.Items.Clear();
            //读取系统的端口初始化端口下拉列表
            string[] portlistOri = SerialPort.GetPortNames();
            string[] portlist = MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
            for (int i = 0; i < portlist.Length; i++)
            {
                for (int k = 0; k < portlistOri.Length; k++)
                {
                    if (portlist[i].Contains(portlistOri[k]))
                    {
                        this.combPortReceive.Items.Add(portlist[i]);
                        this.combPortPrinter.Items.Add(portlist[i]);
                        continue;
                    }
                }

                //this.combPortReceive.Items.Add(portlist[i]);
                //this.combPortPrinter.Items.Add(portlist[i]);
            }
            if (combPortReceive.Items.Count > 0)
            {
                combPortReceive.SelectedIndex = 0;
            }
            if (combPortPrinter.Items.Count > 0)
            {
                combPortPrinter.SelectedIndex = 0;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int n = 99;
            string sss =string.Format("{0:D7}", n);
            
            string ss = System.IO.File.ReadAllText(@"F:\公司项目\C#项目\批量生成条形码并导出为图片\20160506添加序列号版本.prn");//print.txt里写了条码机的命令  F:\公司项目\C#项目\批量生成条形码并导出为图片\20160328.prn
            
        }

        private void btnPrintNum_Click(object sender, EventArgs e)
        {
            FrmPrintNum frm = new FrmPrintNum();
            frm.ShowDialog();
            //MessageBox.Show("123");
            long start = FrmPrintNum.longstart;
            long end = FrmPrintNum.longend;
            DateTime date = FrmPrintNum.pruductionDate;
            if (start == 0)
            {
                return;
            }
            string comSendName = "";
            if (combPortPrinter.SelectedIndex >= 0)
            {
                comSendName = combPortPrinter.Text;
            }
            BarcodePrint zb = new BarcodePrint();
            string mycommanglines = "";

            comSendName = comSendName.Split('(')[1].Split(')')[0];
            if (zb.Open(comSendName))
            {

                for (long i = start; i <= end; i++)
                {
                    mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + i.ToString() + "^FS\r\n^FT97,81^A0N,22,38^FH\\^FDDATE:" + date.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
                    //mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + i.ToString() + "^FS\r\n^FT49,81^A0N,22,38^FH\\^FD生产日期:" + date.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
                    mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n~DG000.GRF,01024,016,\r\n,::::::::::::::::::::::::::::::::I060J0E0N0860,01C70J0F0H07FHF01C67F0,01C60H03FHF802006008E638,01C60H07FHFC0700707FF630,03860I02060020060086630,03FHFC0070F00700701C7730,03060I030C00200600FE7F8,07060I031C00700701C6630,0E060H03FHFE03FFE0086630,I070H07FHFC0700701FE7301C,H0IF8030J02006008E6381E,01FHFH070J0700701C67F01C,I060H020J0200607FE630,I070H070J070070H01F30,I060H060J0200600CCE381E,I060H060J07FHF01C5C301C,07FHFE0E0J0200603078300E,07FIF1C0J070070703CF0,M080J020K01860,,:::::::::::^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + i.ToString() + "^FS\r\n^FT209,83^A0N,19,24^FH\\^FD" + date.ToShortDateString() + "^FS\r\n^FT96,96^XG000.GRF,1,1^FS\r\n^PQ1,0,1,Y^XZ\r\n^XA^ID000.GRF^FS^XZ\r\n";
                    //mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,46^B3N,N,,Y,N\r\n^FD" + "123456789876" + "^FS\r\n^FT330,81^A0N,17,19^FH\\^FD" + SystemConfig.SerialNum + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
                    zb.Write(mycommanglines);
                }
                zb.Close();
            }
            else
            {
                SerialPort serialPortTemp = new SerialPort(comSendName, 9600, Parity.None, 8, StopBits.One);
                serialPortTemp.Open();
                for (long i = start; i <= end; i++)
                {
                    mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + i.ToString() + "^FS\r\n^FT97,81^A0N,22,38^FH\\^FDDATE:" + date.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
                    //mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + i.ToString() + "^FS\r\n^FT49,81^A0N,22,38^FH\\^FD生产日期:" + date.ToShortDateString() + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
                    mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n~DG000.GRF,01024,016,\r\n,::::::::::::::::::::::::::::::::I060J0E0N0860,01C70J0F0H07FHF01C67F0,01C60H03FHF802006008E638,01C60H07FHFC0700707FF630,03860I02060020060086630,03FHFC0070F00700701C7730,03060I030C00200600FE7F8,07060I031C00700701C6630,0E060H03FHFE03FFE0086630,I070H07FHFC0700701FE7301C,H0IF8030J02006008E6381E,01FHFH070J0700701C67F01C,I060H020J0200607FE630,I070H070J070070H01F30,I060H060J0200600CCE381E,I060H060J07FHF01C5C301C,07FHFE0E0J0200603078300E,07FIF1C0J070070703CF0,M080J020K01860,,:::::::::::^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,42^B3N,N,,Y,N\r\n^FD" + i.ToString() + "^FS\r\n^FT209,83^A0N,19,24^FH\\^FD" + date.ToShortDateString() + "^FS\r\n^FT96,96^XG000.GRF,1,1^FS\r\n^PQ1,0,1,Y^XZ\r\n^XA^ID000.GRF^FS^XZ\r\n";
                    //mycommanglines = "CT~~CD,~CC^~CT~\r\n^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD15^JUS^LRN^CI0^XZ\r\n^XA\r\n^MMT\r\n^PW428\r\n^LL0100\r\n^LS0\r\n^BY2,2,24^FT31,46^B3N,N,,Y,N\r\n^FD" + "123456789876" + "^FS\r\n^FT330,81^A0N,17,19^FH\\^FD" + SystemConfig.SerialNum + "^FS\r\n^PQ1,0,1,Y^XZ\r\n";
                    serialPortTemp.WriteLine(mycommanglines);
                }

                serialPortTemp.Close();
            }


        }

        private void btnSetSerialNum_Click(object sender, EventArgs e)
        {
            FrmSetSerialNum frm = new FrmSetSerialNum();
            frm.Show();
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
            {
                combHighTem.Enabled = false;
                combLowTem.Enabled = true;
            }
            else
            {
                combHighTem.Enabled = true;
                combLowTem.Enabled = false;
            }
        }
    }
}
